package com.hardson.toolkit.util;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class RuntimeUtil {

	/**
	 * Java 9 之前获取当前进程 ID
	 */
	public static String getPidBeforeJava9() {
		RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
		String pid = runtimeMXBean.getName().split("@")[0];
		return pid;
	}

	/**
	 * Java 9 获取当前进程 ID
	 */
	/*public static String getPidInJava9() {
		long pid = ProcessHandle.current().pid();
		return String.valueOf(pid);
	}*/

	/**
	 * Java 10 获取当前进程 ID
	 */
	/*public static String getPidInJava10() {
		RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
		long pid = runtimeMXBean.getPid();
		return String.valueOf(pid);
	}
	*/

	/**
	 * 获取进程启动时间(ms)
	 *
	 * @return
	 */
	public static long getStartTime() {
		return ManagementFactory.getRuntimeMXBean().getStartTime();
	}

	/**
	 * 获取进程上线时间(ms)
	 *
	 * @return
	 */
	public static long getUpTime() {
		return ManagementFactory.getRuntimeMXBean().getUptime();
	}

	/**
	 * 获取当前进程活动线程数量
	 *
	 * @return
	 */
	public static long getThreadCount() {
		return ManagementFactory.getThreadMXBean().getThreadCount();
	}

	/**
	 * 获取所有活动线程的线程信息（包括堆栈信息）
	 *
	 * @return
	 */
	public static List<String> getAllThreadsInfo() {
		ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
		List<String> list = Stream.of(threadMXBean.dumpAllThreads(true, true)).map(ThreadInfo::toString)
				.collect(Collectors.toList());
		return list;
	}

	/**
	 * 获取内存相关信息
	 *
	 * @return
	 */
	public static List<String> getMemoryInfo() {
		List<String> list = new ArrayList<>();
		ManagementFactory.getMemoryManagerMXBeans().forEach(b -> {
			StringBuilder info = new StringBuilder(b.getClass().toString() + "(" + b.getName() + ")：\r\n");
			Stream.of(b.getMemoryPoolNames()).forEach(s -> info.append(s).append("\r\n"));
			list.add(info.toString());
		});
		return list;
	}
}
